package com.zsy.petshop_01.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zsy.petshop_01.common.result.ResponseResult;
import com.zsy.petshop_01.service.AlipayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Api(tags = "支付宝管理接口")
@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Autowired
    AlipayService alipayService;
    @Value("${alipay.public-key}")
    private String publicKey;

    @ApiOperation("付款")
    @PostMapping("/pay")
    public ResponseResult<?> initiatePayment(
            @RequestParam String subject,
            @RequestParam String totalAmount,
            HttpServletRequest request
    ) throws AlipayApiException {
        return alipayService.createPaymentOrder(subject, totalAmount, request);
    }

    @ApiOperation("通知")
    @PostMapping("/notify")
    public Map<String, String> handleNotify(HttpServletRequest request) {
        Map<String, String> resultMap = new HashMap<>();
        try {
            // 1. 解析参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = iter.next();
                String[] values = requestParams.get(name);
                params.put(name, values[0]);
            }

            // 2. 验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    publicKey,
                    "UTF-8",
                    "RSA2"
            );

            String result;
            if (signVerified) {
                // 3. 处理支付成功逻辑
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    String outTradeNo = params.get("out_trade_no");
                    String productName = params.get("subject");
                    String totalAmount = params.get("total_amount");
                    String userId = params.get("body");
                    alipayService.updateOrderStatus(outTradeNo, productName, totalAmount, Integer.parseInt(userId));
                    result = "支付成功";
                } else {
                    result = "支付失败";
                }
            } else {
                result = "支付失败";
            }
            resultMap.put("result", result);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", "支付失败");
        }
        return resultMap;
    }

    @ApiOperation(("退款"))
    @PostMapping("/refund")
    public ResponseResult<?> refund(
            @RequestParam String outTradeNo,
            @RequestParam String totalAmount,
            @RequestParam String reason) throws AlipayApiException {
        return alipayService.refund(outTradeNo, totalAmount, reason);
    }
}
